package com.jincheng.springblog.controller;

import com.jincheng.springblog.constant.Constants;
import com.jincheng.springblog.model.Result;
import com.jincheng.springblog.model.UserInfo;
import com.jincheng.springblog.service.UserService;
import com.jincheng.springblog.utils.JwtUtils;
import com.jincheng.springblog.utils.SecurityUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result login(String username, String password){
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)){
            return Result.fail("账号或密码为空");
        }
        UserInfo userInfo = userService.selectByName(username);
        if(userInfo == null){
            return Result.fail("用户不存在");
        }
        if(!SecurityUtils.verify(password, userInfo.getPassword())){
            return Result.fail("密码不正确");
        }
        Map<String, Object> claim = new HashMap<>();
        claim.put(Constants.TOKEN_ID,userInfo.getId());
        claim.put(Constants.TOKEN_USERNAME,userInfo.getUserName());
        String token = JwtUtils.genJwtToken(claim);
        return Result.success(token);
    }

    @RequestMapping("/getUserInfo")
    public UserInfo getLoginUserInfo(HttpServletRequest request){
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        Integer userId = JwtUtils.getIdByToken(token);
        if(userId == null){
            return null;
        }
        return userService.selectById(userId);
    }

    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){
        if(blogId <= 0){
            return null;
        }
        UserInfo userInfo = userService.getAuthorInfo(blogId);
        return userInfo;
    }













}
